<template>
  <div class="connection-manager">
    <div class="header">
      <h2>{{ $t('connections.title') }}</h2>
      <el-button type="primary" icon="el-icon-plus" @click="showConnectionDialog = true">
        {{ $t('connections.newConnection') }}
      </el-button>
    </div>
    
    <div class="connections-list">
      <el-table :data="connectionsWithInfo" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="name" :label="$t('connections.name')" width="180" />
        <el-table-column prop="url" :label="$t('connections.url')" min-width="200" />
        <el-table-column prop="version" :label="$t('connections.version')" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.version">{{ scope.row.version }}</span>
            <span v-else style="color: #909399">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="databaseCount" :label="$t('connections.databases')" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.databaseCount !== undefined">{{ scope.row.databaseCount }}</span>
            <span v-else style="color: #909399">-</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('connections.status')" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="currentConnection && currentConnection.id === scope.row.id ? 'success' : 'info'"
              size="small"
            >
              {{ currentConnection && currentConnection.id === scope.row.id ? $t('connections.active') : $t('connections.inactive') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.actions')" width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="connectToDatabase(scope.row)"
              :disabled="currentConnection && currentConnection.id === scope.row.id"
            >
              {{ $t('common.connect') }}
            </el-button>
            <el-button size="mini" @click="editConnection(scope.row)">
              {{ $t('common.edit') }}
            </el-button>
            <el-button size="mini" type="danger" @click="deleteConnection(scope.row.id)">
              {{ $t('common.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <el-dialog
      :title="editingConnection ? $t('connections.editConnection') : $t('connections.newConnection')"
      :visible.sync="showConnectionDialog"
      width="500px"
    >
      <el-form :model="connectionForm" :rules="connectionRules" ref="connectionForm" label-width="120px">
        <el-form-item :label="$t('connections.name')" prop="name">
          <el-input v-model="connectionForm.name" placeholder="My InfluxDB" />
        </el-form-item>
        
        <el-form-item :label="$t('connections.url')" prop="url">
          <el-input v-model="connectionForm.url" placeholder="http://localhost:8086" />
        </el-form-item>
        
        <el-form-item :label="$t('connections.username')" prop="username">
          <el-input v-model="connectionForm.username" placeholder="Username (optional)" />
        </el-form-item>
        
        <el-form-item :label="$t('connections.password')" prop="password">
          <el-input v-model="connectionForm.password" type="password" placeholder="Password (optional)" />
        </el-form-item>
        
        <el-form-item :label="$t('connections.token')" prop="token">
          <el-input v-model="connectionForm.token" type="password" placeholder="Authentication token (optional)" />
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="testConnection" :loading="testing">{{ $t('connections.testConnection') }}</el-button>
        <el-button @click="showConnectionDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="saveConnection" :loading="saving">
          {{ editingConnection ? $t('common.update') : $t('common.save') }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import i18nMixin from '@/mixins/i18nMixin'

export default {
  name: 'ConnectionManager',
  mixins: [i18nMixin],
  
  data() {
    return {
      showConnectionDialog: false,
      editingConnection: null,
      testing: false,
      saving: false,
      tableLoading: false,
      connectionsWithInfo: [],
      connectionForm: {
        name: 'My InfluxDB',
        url: 'http://localhost:8086',
        token: '',
        username: '',
        password: ''
      },
      connectionRules: {
        name: [
          { required: true, message: 'Please enter a connection name', trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'Please enter the InfluxDB URL', trigger: 'blur' },
          { pattern: /^https?:\/\//, message: 'URL must start with http:// or https://', trigger: 'blur' }
        ]
      }
    }
  },
  
  computed: {
    ...mapState(['connections', 'currentConnection'])
  },
  
  watch: {
    connections: {
      handler() {
        this.updateConnectionsInfo()
      },
      deep: true
    },
    currentConnection() {
      this.updateConnectionsInfo()
    }
  },
  
  mounted() {
    this.loadConnections().then(() => {
      this.updateConnectionsInfo()
    })
  },
  
  methods: {
    ...mapActions([
      'loadConnections',
      'saveConnection',
      'removeConnection',
      'setCurrentConnection',
      'testConnection',
      'getDatabases',
      'getServerInfo'
    ]),
    
    editConnection(connection) {
      this.editingConnection = connection
      this.connectionForm = { ...connection }
      this.showConnectionDialog = true
    },
    
    async deleteConnection(id) {
      try {
        await this.$confirm(this.$t('connections.deleteConfirm'), this.$t('common.warning'), {
          confirmButtonText: this.$t('common.delete'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
        
        await this.removeConnection(id)
        this.$message.success(this.$t('connections.deleteSuccess'))
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(this.$t('connections.deleteFailed'))
        }
      }
    },
    
    async connectToDatabase(connection) {
      try {
        // First test the connection
        const testResult = await this.$store.dispatch('testConnection', {
          ...connection,
          queryType: 'influxql'
        })
        
        if (testResult && testResult.success) {
          const success = await this.setCurrentConnection(connection)
          if (success) {
            this.$message.success('Connected successfully to InfluxDB')
            await this.updateConnectionsInfo()
          } else {
            this.$message.error('Failed to set as current connection')
          }
        } else {
          const errorMessage = testResult && testResult.message 
            ? testResult.message 
            : 'Cannot connect to InfluxDB at ' + connection.url
          this.$message.error('Connection failed: ' + errorMessage)
        }
      } catch (error) {
        this.$message.error('Connection failed: ' + error.message)
      }
    },
    
    async updateConnectionsInfo() {
      this.tableLoading = true
      const updatedConnections = []
      
      for (const conn of this.connections) {
        const connectionInfo = { ...conn }
        
        // Only fetch info for the active connection
        if (this.currentConnection && this.currentConnection.id === conn.id) {
          try {
            // Fetch databases and server info
            const [databases, serverInfo] = await Promise.all([
              this.getDatabases().catch(() => []),
              this.getServerInfo().catch(() => null)
            ])
            
            connectionInfo.databaseCount = databases ? databases.length : 0
            connectionInfo.version = serverInfo ? serverInfo.version : '-'
          } catch (error) {
            console.error('Failed to load connection info:', error)
            connectionInfo.databaseCount = 0
            connectionInfo.version = '-'
          }
        }
        
        updatedConnections.push(connectionInfo)
      }
      
      this.connectionsWithInfo = updatedConnections
      this.tableLoading = false
    },
    
    async testConnection() {
      this.$refs.connectionForm.validate(async (valid) => {
        if (!valid) return
        
        this.testing = true
        try {
          const result = await this.$store.dispatch('testConnection', {
            ...this.connectionForm,
            queryType: 'influxql'  // Always use InfluxQL
          })
          if (result.success) {
            this.$message.success('Connection test successful!')
          } else {
            this.$message.error('Connection test failed: ' + result.message)
          }
        } catch (error) {
          this.$message.error('Connection test failed: ' + error.message)
        } finally {
          this.testing = false
        }
      })
    },
    
    async saveConnection() {
      this.$refs.connectionForm.validate(async (valid) => {
        if (!valid) return
        
        this.saving = true
        try {
          // Check for duplicate URL
          const isDuplicate = this.connections.some(conn => {
            // Skip checking against itself when editing
            if (this.editingConnection && conn.id === this.editingConnection.id) {
              return false
            }
            return conn.url.toLowerCase() === this.connectionForm.url.toLowerCase()
          })
          
          if (isDuplicate) {
            this.$message.warning(this.$t('connections.duplicateUrl'))
            this.saving = false
            return
          }
          
          if (this.editingConnection) {
            this.connectionForm.id = this.editingConnection.id
          }
          
          // Always set queryType to influxql
          const connectionData = {
            ...this.connectionForm,
            queryType: 'influxql'
          }
          
          await this.$store.dispatch('saveConnection', connectionData)
          this.$message.success(this.$t('connections.saveSuccess'))
          this.showConnectionDialog = false
          this.resetForm()
        } catch (error) {
          this.$message.error(this.$t('connections.saveFailed') + ': ' + error.message)
        } finally {
          this.saving = false
        }
      })
    },
    
    resetForm() {
      this.editingConnection = null
      this.connectionForm = {
        name: 'My InfluxDB',
        url: 'http://localhost:8086',
        token: '',
        username: '',
        password: ''
      }
      this.$refs.connectionForm && this.$refs.connectionForm.resetFields()
    }
  }
}
</script>

<style scoped>
.connection-manager {
  padding: 30px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e2e8f0;
}

.header h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  letter-spacing: -0.5px;
}

.header .el-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(102, 126, 234, 0.3);
}

.header .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4);
}

.connections-list {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.connections-list:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.connections-list .el-table {
  font-size: 14px;
}

.connections-list .el-table th {
  background: #f8fafc !important;
  color: #475569;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
}

.connections-list .el-table tr {
  transition: all 0.3s;
}

.connections-list .el-table tr:hover td {
  background: #f8fafc !important;
}

.connections-list .el-button--primary {
  background: #3b82f6;
  border-color: #3b82f6;
}

.connections-list .el-button--danger {
  background: #ef4444;
  border-color: #ef4444;
}

/* Dialog styles */
.el-dialog {
  border-radius: 12px;
}

.el-dialog__header {
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  padding: 20px;
  border-radius: 12px 12px 0 0;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.el-dialog__footer {
  padding: 20px;
  border-top: 1px solid #e2e8f0;
  background: #f8fafc;
  border-radius: 0 0 12px 12px;
}
</style>